<?php

class Auth {

    protected $dbo = NULL;

    public function __construct() {

        $this->dbo  = &DBO::getInstance();
    }

    public function getLangAuto() {

        $res = $this->dbo->getOne("select country from sys.geoip WHERE net >> ?::inet",
            array(
                DBString::create($_SERVER['REMOTE_ADDR'])
            ),
            DB_FETCHMODE_ASSOC);

        throwOnError($res);

        if(empty($res)) {
            return 'en';
        } else {
            return $res;
        }

    }

    public function registerUser($login, $password, $email) {

        $user2 = new User;

        if(User::exists($login))
            throw new Exception(_('User').' '.$login._(' already registered.'));
            
        if(User::emailExists($email))
            throw new Exception(_('Email').' '.$email._(' already exists.'));

        $user2->name = $login;
        $user2->password = md5(PASSWORD_KEY . $password);
        $user2->email = $email;
        $user2->banned = false;
        $user2->registration_date = date('Y-m-d H:m:s');
        $user2->registration_ip = $_SERVER['REMOTE_ADDR'];
        $user2->last_login = NULL;
        $user2->access = 1;
        $user2->cookie = md5(PASSWORD_KEY . time());
        $user2->lang = $this->getLangAuto();

        $user2->save();

        return $user2;
        
    }

    public function loginUser($login, $password) {

        $user = new User;

        $user->name = $login;
        $user->password = md5(PASSWORD_KEY . $password);

        try {
            if(!$user->loadByName())
                throw new Exception(_('Invalid login/password.'));

        } catch (Exception $e){

            throw new Exception(_('Invalid login/password.'));
        }

        $_SESSION['cookie'] = $user->cookie;

        return $user;
    }

    public function logoutUser() {

        session_destroy();
    }
}